import './App.css';
import {Input, Tree} from "antd";
import {useEffect, useState} from "react";
import {
  DownOutlined,
} from '@ant-design/icons';
import Storage from "./utils/storage";
import Tabs from "./utils/tabs";
import Bookmarks from "./utils/bookmarks";

function App() {
  const [bookmarksList, setBookmarksList] = useState([])
  const [allbookmarks, setAllBookmarks] = useState([])
  const [expandedKeys, setexpandedKeys] = useState([])

  // 加载全部书签
  const loadBookmarks = async () => {
    let res = await Bookmarks.getTree()
    let result = res[0].children || []
    setBookmarksList(result)
    setAllBookmarks(result)
  }

  useEffect(() => {
    loadBookmarks()
  }, [])

  const onSelect = async (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
    setexpandedKeys(selectedKeys)
    if (!info.node.url) return
    let bookmarkNode = info.node

    const mapping = await Storage.get(bookmarkNode.id) || {}
    let tab = mapping[bookmarkNode.id]
    if (!Object.keys(mapping).length || !tab) {
      console.log('not find in mapping')
      createTab(bookmarkNode)
      return
    }

    const currentTabs = await Tabs.query()
    if (currentTabs.every(item => item.id !== tab.id)) {
      console.log('not find in tabs')
      createTab(bookmarkNode)
      return
    }

    // 定位到书签页
    chrome.tabs.highlight({tabs: tab.index})
  };

  const onSearchBookmark = (value) => {
    if (value) {
      chrome.bookmarks.search(value, (res) => {
        setBookmarksList(res)
      })
    } else {
      setBookmarksList(allbookmarks)
    }
  }

  const getIcon = (url = '') => {
    let reg = /^http(s)?:\/\/(.*?)\//
    let result = url.match(reg) || []
    let iconsArray = ['conf', 'google', 'baidu', 'captain', 'github', 'git', 'npm', 'ctripcorp', 'ant']
    let icon = ''
    if (result.length) {
      iconsArray.forEach(website => {
        if (icon) {
          return
        }
        if (result[0].indexOf(website) !== -1) {
          icon = website
          return
        }
      })
    }

    if (icon) {
      return <img src={require(`./icons/${icon}.ico`)} className={'icon'}/>
    }

    return null
  }


  return (
    <div className="App">
      <div className="flex">
        <div className="title">Search Bookmark</div>
        <div>
          <Input onChange={e => onSearchBookmark(e.target.value)}/>
        </div>
      </div>

      <div>
        <Tree
          showIcon
          showLine
          switcherIcon={<DownOutlined/>}
          treeData={bookmarksList}
          onSelect={onSelect}
          expandedKeys={expandedKeys}
          titleRender={(node) => {
            return <div className="tree-title">
              {getIcon(node.url)}
              <span>{node.title}</span>
            </div>
          }}
        />
      </div>
    </div>
  );
}

async function createTab(bookmarkNode) {
  let tab = await Tabs.create({
    url: bookmarkNode.url,
    active: false
  })
  Storage.save({
    [bookmarkNode.id]: tab
  })

  return tab
}

export default App;
